import {Component, OnInit} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {CommodityInfoService} from './commodity-info.service';
import {PermissionService} from '../../../../../service/permission.service';


@Component({
  selector: 'app-commodity-info',
  templateUrl: './commodity-info.component.html',
  styleUrls: ['./commodity-info.component.scss']
})
export class CommodityInfoComponent implements OnInit {

  isCollapse: boolean = false;
  /**
   * 列表数据源
   */
  listOfData?: any;
  /**
   * 查询load动画
   */
  isLoadingOne = false;
  /**
   * 当前是否在搜索
   */
  searchHint = false;
  /**
   * 商品分类下拉
   */
  GoodsTypeList: any = [];
  /**
   * 品牌下拉
   */
  BrandList: any = null;
  /**
   * 当前搜索name
   */
  searchName = '';
  /**
   * 表单load动画
   */
  tableLoading: boolean = false;
  /**
   * 加载失败显示图像占位符
   */
  fallback =
    '';
  /**
   * 查询参数
   */
  queryForm: any = {
    // 商品分类
    type: [],
    // 品牌ID
    brandId: [],
    // 开始时间
    updateBeginTime: '',
    // 结束时间
    updateEndTime: '',
    // 时间区间
    dateFormat: [],
    // 69码
    code: '',
    exsistBom: false,
    exsistSN: null,
    exsistWarning: false,
    page: 1,
    pageSize: 20,
    // // 0 默认方式   1实际库存  2不良品库存
    // whGoodsSort: 0,
    // // true 正序  false 倒序
    // asc: true
  };
  /**
   * 全局 loading
   */
  messageId: any = null;
  /**
   * 路由缓存恢复时
   */
  static updateCache: any = null;
  typeCheckAll = false;

  cacheData: any = {
    brandIdList: [],
    typeList: [107]
  };

  constructor(
    private warehouseGoodsService: CommodityInfoService,
    private message: NzMessageService,
    public permission: PermissionService,
  ) {
  }

  ngOnInit() {
    CommodityInfoComponent.updateCache = () => {
      this.tableLoading = false;
      this.getGoodsList();
      this.getBrandList();
      this.getGoodsTypeList();
    };
    this.getGoodsList();
    this.getBrandList();
    this.getGoodsTypeList();
  }

  /**
   * 查询
   */
  query() {
    // this.queryForm.whGoodsSort = 0;
    // this.queryForm.asc = true;
    console.log(this.queryForm.type);
    this.queryForm.page = 1;
    this.getGoodsList();
  }

  // 重置
  resetTable() {
    this.typeCheckAll = false;
    this.queryForm = {
      // 商品分类
      type: [],
      // 品牌ID
      brandId: [],
      // 开始时间
      updateBeginTime: '',
      // 结束时间
      updateEndTime: '',
      // 时间区间
      dateFormat: [],
      // 69码
      code: '',
      exsistBom: false,
      exsistSN: null,
      exsistWarning: false,
      page: 1,
      pageSize: 20,
      // // 0 默认方式   1实际库存  2不良品库存
      // whGoodsSort: 0,
      // // true 正序  false 倒序
      // asc: true
    };
    this.getGoodsList();
  }

  /**
   * 搜索返回原列表
   */
  backList() {
    this.queryForm = {
      // 商品分类
      type: [],
      // 品牌ID
      brandId: [],
      // 开始时间
      updateBeginTime: '',
      // 结束时间
      updateEndTime: '',
      // 时间区间
      dateFormat: [],
      // 69码
      code: '',
      exsistBom: false,
      exsistSN: null,
      exsistWarning: false,
      page: 1,
      pageSize: 20,
      // // 0 默认方式   1实际库存  2不良品库存
      // whGoodsSort: 0,
      // // true 正序  false 倒序
      // asc: true
    };
    this.getGoodsList();
  }

  /**
   * 页码改变
   * @param index 页码数
   */
  onPageIndexChange(index: number) {
    // console.log(index);
    this.queryForm.page = index;
    this.getGoodsList();
  }

  /**
   * 每页条数改变的回调
   * @param index 页码数
   */
  onPageSizeChange(index: number) {
    this.queryForm.pageSize = index;
    this.getGoodsList();
    // console.log(index);
  }

  /**
   * 同步
   */
  synchro() {
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.warehouseGoodsService.itemSynchronize().subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', res.message);
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 同步商品库存
   */
  synchroStore() {
    if (this.messageId != null) {
      return;
    }
    this.createBasicMessage();
    this.warehouseGoodsService.stockInventoryQuery().subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '同步商品库存成功');
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  getGoodsList() {
    if (this.tableLoading) {
      return;
    }
    this.listOfData = [];
    this.tableLoading = true;
    const list: any[] = [];
    this.GoodsTypeList.forEach((item: any) => {
      if (this.queryForm.type.includes(item.key)) {
        this.getAllChildren(item, list);
      }
      if (item.children.length) {
        this.foreachType(item, this.queryForm.type, list);
      }
    });

    this.warehouseGoodsService.getList({...this.queryForm, type: list}).subscribe((res: any) => {
      this.listOfData = res.data;

      // let textArr = [];
      // if (this.queryForm.name) {
      //   textArr.push(this.queryForm.name);
      // }
      // if (this.queryForm.code) {
      //   textArr.push(this.queryForm.code);
      // }
      // if (this.queryForm.attr) {
      //   textArr.push(this.queryForm.attr);
      // }
      // if (this.queryForm.brandId) {
      //   textArr.push(this.queryForm.brandId);
      // }
      // if (this.queryForm.type) {
      //   textArr.push(this.queryForm.type);
      // }
      // if (this.queryForm.dateFormat) {
      //   textArr.push(this.queryForm.dateFormat);
      // }
      // this.searchName = textArr.join(' | ');

      this.isLoadingOne = false;

      for (let index = 0; index < this.listOfData?.records?.length; index++) {
        const element = this.listOfData.records[index];
        element.stateText = this.state_To_text(element.state);
      }
      this.tableLoading = false;
    }, err => {
      this.tableLoading = false;
    });
  }

  /**
   * 商品分类下拉
   */
  getGoodsTypeList() {
    this.warehouseGoodsService.getGoodsTypeList().subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      // this.GoodsTypeList = res.data;
      this.GoodsTypeList = this.addFieldArr(res.data);
      console.log(this.GoodsTypeList);
    }, err => {
      this.createMessage('error', '请求失败');

    });
  }

  /**
   * 商品 品牌下拉
   */
  getBrandList() {
    this.warehouseGoodsService.getBrandList({name: '', page: 1, pageSize: 999999}).subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.BrandList = res.data.records;
    }, err => {

    });
  }

  // 品牌 全选
  onSelectBrandAll(ev: any) {
    if (ev.includes('all')) {
      this.cacheData.brandIdList = [];
      this.BrandList.forEach((element: any) => {
        const {id} = element;
        if (id) {
          this.cacheData.brandIdList.push(`${id}`);
        }
      });
    }
    this.queryForm.brandId = this.cacheData.brandIdList;
  }

  // 类型 全选
  onSelectTypeAll(ev: any) {
    if (ev.includes('all')) {
      this.cacheData.typeList = [];
      this.GoodsTypeList.forEach((element: any) => {
        const {id} = element;
        if (id) {
          this.cacheData.typeList.push(`${id}`);
        }
      });
    }
    this.queryForm.type = this.cacheData.typeList;
  }

  // 0 默认方式   1实际库存  2不良品库存
  // asc true-升序排序、false-降序排序
  onTableFilter(val: any) {
    // this.queryForm.whGoodsSort = val;
    // this.queryForm.asc = !this.queryForm.asc;
    this.getGoodsList();
  }

  /**
   * 确认删除
   * @param id 商品id
   */
  confirm(id: any = null) {
    if (this.messageId != null) {
      return;
    }

    this.createBasicMessage();
    this.warehouseGoodsService.del({id}).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      this.createMessage('success', '删除成功');
      this.getGoodsList();
    }, err => {
      this.isLoadingOne = false;
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 状态转文字
   * @param state
   */
  state_To_text(state: any) {
    let text = '';
    switch (state) {
      case 0:
        text = '草稿';
        break;
      case 1:
        text = '待审核';
        break;
      case 2:
        text = '审核通过';
        break;
      case 3:
        text = '审核不通过';
        break;
      default:
        text = '-';
        break;
    }
    return text;
  }

  // 分类下拉数据处理
  addFieldArr(arr: any) {
    return arr.map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = this.addFieldArr(item.children);
      }
      item.isLeaf = item.children && item.children.length === 0;
      return {
        // disabled: item.state === 1,
        isLeaf: item.isLeaf,
        children: item.children,
        state: item.state,
        key: item.id + '',
        title: item.name
      };
    });
  }

  // 分类选择
  onChangeTree(event: any) {
    // console.log('selected type', event);
    if (event) {
      // this.queryForm.type = this.cacheData.typeList.join(',');
      this.queryForm.type = this.cacheData.typeList;
    }
  }

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', {nzDuration: 0}).messageId;
  }

  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning:警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  typeChange(event: any): void {
    console.log(event.keys);
    console.log(this.queryForm.type);
    this.queryForm.type = event.keys;
    // this.queryForm.type = [];
    // const list: any[] = [];
    // this.GoodsTypeList.forEach((item: any) => {
    //   if (event.keys.includes(item.key)) {
    //     this.getAllChildren(item, list);
    //   }
    //   if (item.children.length) {
    //     this.foreachType(item, event.keys, list);
    //   }
    // });
    // this.queryForm.type = list;
    this.getGoodsList();
  }

  foreachType(item: any, keys: any[], list: any[]) {
    item.children.forEach((i: any) => {
      if (keys.includes(i.key)) {
        this.getAllChildren(i, list);
      }
      if (i.children.length) {
        this.foreachType(i, keys, list);
      }
    });
  }

  getAllChildren(item: any, list: any[]) {
    list.push(item.key);
    item.children.forEach((i: any) => {
      this.getAllChildren(i, list);
    });
  }

  getAllType() {
    this.queryForm.type = [];
    if (this.typeCheckAll) {
      const list: any[] = [];
      this.GoodsTypeList.forEach((item: any) => {
        this.getAllChildren(item, list);
      });
      this.queryForm.type = list;
    }
    this.getGoodsList();
  }
}
